/**
 * @file Login.vue
 * @description 登录页面组件，采用现代简约设计风格
 * @created 2024-03-20
 */

<template>
  <div class="login-container">
    <!-- 动态背景 -->
    <div class="background">
      <div class="mountains">
        <div class="mountain-front"></div>
        <div class="mountain-mid"></div>
        <div class="mountain-back"></div>
      </div>
      <div class="sun"></div>
      <div class="stars"></div>
      <div class="clouds">
        <div class="cloud cloud1"></div>
        <div class="cloud cloud2"></div>
        <div class="cloud cloud3"></div>
      </div>
    </div>
    <!-- 登录框 -->
    <div class="login-box">
      <!-- Logo区域 -->
      <div class="logo">
        <div class="logo-text">
          <h1>华侨大学</h1>
          <p>智能教学服务系统</p>
        </div>
      </div>

      <!-- 角色选择 -->
      <div class="role-selector">
        <div class="role-item"
             :class="{ active: currentRole === 'student' }"
             @click="currentRole = 'student'">
          <span class="icon">👨‍🎓</span>
          <span>学生端</span>
        </div>
        <div class="role-item"
             :class="{ active: currentRole === 'teacher' }"
             @click="currentRole = 'teacher'">
          <span class="icon">👨‍🏫</span>
          <span>教师端</span>
        </div>
        <div class="role-item"
             :class="{ active: currentRole === 'admin' }"
             @click="currentRole = 'admin'">
          <span class="icon">👨‍💼</span>
          <span>管理端</span>
        </div>
      </div>

      <!-- 登录表单 -->
      <div class="input-group" :rules="rules">
        <div class="input-item">
          <span class="input-icon">👤</span>
          <input type="text" v-model="username" :placeholder="getPlaceholder">
        </div>
        <div class="input-item" :rules="rules">
          <span class="input-icon">🔒</span>
          <input type="password" v-model="password" placeholder="请输入密码">
        </div>
      </div>

      <button class="login-btn" @click="handleLogin" :disabled="loading">
        {{ loading ? '登录中...' : '登 录' }}
      </button>

      <div class="footer-links">
        <a href="#" class="link">在线帮助</a>
        <a href="#" class="link">忘记密码</a>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/modules/user'
import axios from 'axios'
import { ElMessage } from "element-plus"
import { authAPI } from '@/api/admin/auth'
import { student_auth_api } from '@/api/student/student_login'
import { useAuthStore } from '@/stores/student_auth'


const router = useRouter()
const username = ref('')
const password = ref('')
const currentRole = ref('student')
const userStore = useUserStore()
const authStore = useAuthStore()
const loading = ref(false)


const rules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 5, max: 10, message: '用户名必须是5-10为的字符', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位非空字符',
      trigger: 'blur'
    }
  ]
}
// 根据角色显示不同的placeholder
const getPlaceholder = computed(() => {
  switch(currentRole.value) {
    case 'student': return '请输入学号'
    case 'teacher': return '请输入工号'
    case 'admin': return '请输入管理员账号'
    default: return '请输入账号'
  }
})

const handleLogin = async () => {
  try {
    // 简单的账号密码验证
    if (!username.value || !password.value) {
      ElMessage.error('请输入账号和密码')
      return
    }

    // 设置加载状态
    loading.value = true

    if (currentRole.value === 'admin') {
      // 调用真实的管理员登录API
      const response = await authAPI.login({ username: username.value, password: password.value })
      console.log('管理员真实登录API响应:', response)

      if (response && response.data && response.status === 'success') { // 或者根据您API成功响应的实际结构判断
        // 使用统一的登录成功处理函数，传入从后端获取的真实数据
        await userStore.handleLoginSuccess({
          token: response.data.token,
          username: response.data.username,
          role: response.data.role,
          id: response.data.user_id
        })
        // 导航到管理员首页或相关页面
        // router.push('/admin/home') // 或其他管理员默认页
      } else {
        // API调用成功但业务逻辑失败 (例如，后端返回 status: 'error')
        ElMessage.error(response.message || '管理员登录失败，请检查响应数据')
        console.error('管理员登录业务逻辑失败:', response)
      }

    } else if (currentRole.value === 'student') {
      // 学生登录逻辑 (如果也需要对接真实API，按类似方式修改)
      // 此处暂时保留原来的模拟逻辑，或根据需要修改
      const studentResponse = await student_auth_api.login({ username: username.value, password: password.value });
      console.log('学生真实登录API响应:', studentResponse);

      if (studentResponse && studentResponse.data && studentResponse.code === 200) {
        // await authStore.loginSuccess(studentResponse.data); // 使用 student_auth store
        // router.push('/student/dashboard'); // 学生仪表盘
          localStorage.setItem('studentUserInfo', JSON.stringify(studentResponse.data));
          router.push('/student/Homepage/PersonalHomepage')
      } else {
        ElMessage.error(studentResponse.message || '学生登录失败');
        console.error('学生登录业务逻辑失败:', studentResponse);
      }

    } else if (currentRole.value === 'teacher') {
      // 教师登录逻辑 (如果也需要对接真实API，按类似方式修改)
      // 此处暂时保留原来的模拟逻辑，或根据需要修改
       ElMessage.info('教师端登录功能正在开发中...')
      // 示例：
      // const teacherResponse = await teacherAPI.login({ username: username.value, password: password.value });
      // if (teacherResponse && teacherResponse.data && teacherResponse.status === 'success') {
      //   await userStore.handleLoginSuccess({ ...teacherResponse.data });
      //   router.push('/teacher/dashboard');
      // } else {
      //   ElMessage.error(teacherResponse.message || '教师登录失败');
      // }
    }
  } catch (error) {
    console.error('登录失败:', error)
    // 打印详细的错误信息以便调试
    if (error.response) {
      // 服务器返回了错误响应
      console.error('服务器响应:', error.response.status, error.response.data)
    } else if (error.request) {
      // 请求发送了但没有收到响应
      console.error('未收到响应，请求详情:', error.request)
    } else {
      // 请求错误
      console.error('请求错误:', error.message)
    }

    ElMessage.error(error.response?.data?.message || '登录失败，请检查账号和密码')
  } finally {
    // 无论成功失败，都关闭加载状态
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  width: 100vw;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

/* 背景动画 */
.background {
  position: absolute;
  width: 100%;
  height: 100%;
  background: linear-gradient(180deg, #22223b 0%, #4a4e69 100%);
  overflow: hidden;
}

/* 云朵动画 */
.clouds {
  position: absolute;
  width: 100%;
  height: 100%;
}

.cloud {
  position: absolute;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 100px;
  animation: float linear infinite;
}

.cloud1 {
  width: 200px;
  height: 60px;
  top: 20%;
  animation-duration: 30s;
}

.cloud2 {
  width: 150px;
  height: 40px;
  top: 40%;
  animation-duration: 20s;
  animation-delay: -15s;
}

.cloud3 {
  width: 180px;
  height: 50px;
  top: 30%;
  animation-duration: 25s;
  animation-delay: -7s;
}

@keyframes float {
  from { left: -20%; }
  to { left: 120%; }
}

/* 登录框样式 */
.login-box {
  position: relative;
  width: 50%;
  max-width: 600px;
  min-width: 400px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(8px);
}

/* 角色选择器 */
.role-selector {
  display: flex;
  justify-content: space-between;
  margin: 30px 0;
  background: #f8f9fa;
  border-radius: 12px;
  padding: 8px;
}

.role-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 12px;
  cursor: pointer;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.role-item .icon {
  font-size: 24px;
}

.role-item:hover {
  background: rgba(74, 78, 105, 0.1);
}

.role-item.active {
  background: #4a4e69;
  color: white;
}

/* 输入框组 */
.input-item {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-radius: 12px;
  padding: 12px 16px;
  margin-bottom: 15px;
}

.input-icon {
  font-size: 20px;
  margin-right: 12px;
  color: #666;
}

input {
  flex: 1;
  border: none;
  background: transparent;
  outline: none;
  font-size: 16px;
  color: #333;
}

.login-btn {
  width: 100%;
  padding: 16px;
  margin: 25px 0;
  background: #4a4e69;
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 18px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.login-btn:hover {
  background: #22223b;
}

.login-btn:disabled {
  background: #9a9db8;
  cursor: not-allowed;
}

/* 底部链接 */
.footer-links {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.link {
  color: #4a4e69;
  text-decoration: none;
  transition: color 0.3s;
}

.link:hover {
  color: #22223b;
  text-decoration: underline;
}

/* LOGO样式 */
.logo {
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo-image {
  width: 80px;
  height: 80px;
  margin-right: 16px;
}

.logo-text {
  text-align: center;
}

.logo-text h1 {
  color: #22223b;
  margin: 0;
  font-size: 28px;
  margin-bottom: 4px;
}

.logo-text p {
  color: #4a4e69;
  margin: 0;
  font-size: 16px;
}

/* 山脉背景 */
.mountains {
  position: absolute;
  bottom: 0;
  width: 100%;
}

.mountain-front, .mountain-mid, .mountain-back {
  position: absolute;
  bottom: 0;
  border-radius: 50%;
}

.mountain-back {
  height: 30vh;
  width: 120%;
  left: -10%;
  background: rgba(43, 45, 66, 0.8);
}

.mountain-mid {
  height: 25vh;
  width: 130%;
  left: -15%;
  background: rgba(43, 45, 66, 0.6);
}

.mountain-front {
  height: 20vh;
  width: 140%;
  left: -20%;
  background: rgba(43, 45, 66, 0.4);
}

/* 太阳 */
.sun {
  position: absolute;
  top: 15%;
  right: 15%;
  width: 80px;
  height: 80px;
  background: rgba(255, 209, 102, 0.8);
  border-radius: 50%;
  box-shadow: 0 0 60px rgba(255, 209, 102, 0.6);
}

/* 星星 */
.stars {
  position: absolute;
  width: 100%;
  height: 100%;
  background-image: radial-gradient(white 1px, transparent 0);
  background-size: 50px 50px;
  opacity: 0.5;
}
</style>
